import json
import string

from django.db import connection
from django.shortcuts import render
from rest_framework.permissions import IsAuthenticated, IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView
from utils.MyBaseView import send_email
from ticket.models import *
# Create your views here.

from myapp.models import *

#导入上传文件夹配置
from mydjango.settings import UPLOAD_ROOT
import os


#创建工单
from workorder.views import dictfetchall


class FlowConView(APIView):
    permission_classes = [IsAdminUser]

    def post(self, request):
        # 1.接收数据
        flowconf_id = request.data.get('flowconf_id')
        parameter = request.data

        # 2.实例化工单
        workorder = WorkOrder.objects.create(
            flowconf_id=flowconf_id,
            create_user=request.user,
            parameter=json.dumps(parameter)
        )


        data = {
            "msg":"创建工单完成",
            "results": {
                'workorder_id': workorder.id,
            }
        }
        return Response(data)


class CarefulView(APIView):
    def post(self, request):
        id = request.data.get("id")
        # start = request.data.get("start")
        # print(start)
        obj = WorkOrder.objects.get(id=id)
        obj.order_status += 1
        obj.save()
        return Response({"msg": "审批通过", 'code': 200})

    def get(self, request):
        id = request.GET.get("id")
        # start = request.GET.get("start")
        obj = WorkOrder.objects.get(id=id)
        obj.order_status = 1
        obj.save()
        return Response({"msg": "审核被退回", 'code': 400})





#文件上传
class Uploader(View):

	def post(self,request):

		#接收文件
		file = request.FILES.get("file")

		#写文件
		with open(os.path.join(UPLOAD_ROOT,'',file.name),'wb') as f:
			for chunk in file.chunks():
				f.write(chunk)

		return HttpResponse(json.dumps({'filename':file.name},ensure_ascii=False),content_type='application/json')

    #
    # class Allobj(APIView):
    #     def get(self,request):
    #         id = request.data.get('approver')

class Stack:
    def __init__(self):
        self.item = []
    def push(self,item):
        self.item.append(item)
    def pop(self):
        return self.item.pop()

#  bin 方法
class Stacks:
    def __init__(self):
        self.items = []

    def push(self, item):
        while True:
            a = item % 2
            self.items.append(a)
            item = item // 2
            if item == 0:
                break

    def pop(self):
        # my_len = len(self.items)
        # my_list = []
        while True:
            if len(self.items) != 0:
                print(self.items.pop(), end='')
            else:
                break
    def get(self):
        return self.items


stact_bin = Stack()

stact_bin.push(12)

stact_bin.pop()


class MyWorkOrder(APIView):
    def get(self,request):
        uid = request.GET.get("uid")
        # 建立查询游标
        cursor = connection.cursor()
        # 使用SQL语句查询该用户所拥有的工单
        cursor.execute(
            "SELECT * FROM WorkOrder WHERE username=%s"%uid
        )
        # 获取结果集
        res = dictfetchall(cursor)
        my_lisy = []
        for i in res:
            data = {}
            data['yyy'] = eval(i['yyy'])
            data["descrip"] = i['descrip']
            data["id"] = i['id']
            my_lisy.append(data)
        print(my_lisy)
        return Response(my_lisy)






# my = [1, 7]
#
# my_len = int(len(my)-1)
# print(my_len, '----------')
#
# for i in range(0,10):
#     if int(my_len) >= i:
#         print(my[i])
#
# # print(my[0],my[1])

#
# from abc import ABCMeta, abstractclassmethod
#
#
# class Employee(metaclass=ABCMeta):
#     """员工抽象基类"""
#
#     def __init__(self, name, descrip, role):
#         self.name = name
#         self.descrip = descrip
#         self.role = role
#
#     @abstractclassmethod
#     def get_role(self):
#         pass
#
#     def __str__(self):
#         return f"{self.__class__.__name__} - {self.name}, {self.descrip} years old {self.role}"
#
#
# class Engineer(Employee):
#     """继承抽象基类，重写抽象方法: 定义员工"""
#
#     def get_role(self):
#         return "engineering"
#
#
# class Accountant(Employee):
#     """继承抽象基类，重写抽象方法: 定义员工"""
#
#     def get_role(self):
#         return "accountant"
#
#
# class Admin(Employee):
#     """继承抽象基类，重写抽象方法: 定义员工"""
#
#     def get_role(self):
#         return "administration"
#
#
# class EmployeeFactory:
#     """定义员工工厂类"""
#
#     @classmethod
#     def create(cls, name, *args):
#         """生成员工实例的工厂方法"""
#         name = name.lower().strip()
#
#         if name == 'engineer':
#             return Engineer(*args)
#         elif name == 'accountant':
#             return Accountant(*args)
#         elif name == 'admin':
#             return Admin(*args)


class Factory:
    def __init__(self, qid, state):
        self.yd = Qinjia.objects.filter(id=qid)
        self.qingjia_info = self.yd.first()
        self.pid = eval(self.qingjia_info.pid)
        self.qid = qid  # 关联表里的qid
        self.state = state  # 审批状态码

    # 串审
    def Chuan(self, state):
        if state != 2:
            # 清空当前改申请单的三方关联信息
            YD.objects.filter(qid=self.qid).delete()
            # 新建三方关联信息
            YD.objects.create(qid=self.qid, pid=self.pid)
            self.yd.update(pid=str(self.pid), state=3)
        else:
            # 清空当前改申请单的三方关联信息
            YD.objects.filter(qid=self.qid).delete()
            # 新建三方关联信息
            YD.objects.create(qid=self.qid, pid=self.pid)
            self.yd.update(pid=str(self.pid), state=2)

    def Bing(self, state):
        if state != 2:
            YD.objects.filter(qid=self.qid).delete()
            for i in self.pid:
                YD.objects.create(qid=self.qid, pid=i)
            self.yd.update(pid=self.pid, state=3)
        else:

            YD.objects.filter(qid=self.qid).delete()
            for i in self.pid:
                YD.objects.create(qid=self.qid, pid=i)
            self.yd.update(pid=self.pid, state=2)

import random

class WD(APIView):
    def get(self,request):
        obj = request.data.get('id')
        qing = Qinjia.objects.filter(uid=id,qingqiu = 3)
        num = len(qing)
        # num = count



    def post(self,request):
        img = request.data.get('img')
        user_id = request.data.get('user_id')
        ping = request.data.get('ping')
        state = request.data.get('state')
        Stea.objects.create(img=img,user_id=user_id,ping=ping,state=state)
        sui = ''.join(random.sample(string.digits,4))
        red = user_id + sui
        r.hmset(red,{'uid':user_id,'ping':ping})
        r.sadd(user_id,sui)
        r.expire(red,120)
        return Response({'data':'成功'})



class CX(APIView):
    def get(self,request):
        obj = Stea.objects.all().order_by()
        data_list = []
        for lis in obj:
            tup = {}
            tup['id'] = lis.id
            tup['ping'] = lis.ping
            tup['user_id'] = User.objects.get('user_id')
            tup['img'] = lis.img
            tup['state'] = lis.state
            data_list.append(tup)
        return Response({'data':data_list})


    def put(self,request):
        id = request.data.get('id')
        user_id = request.data.get('user_id')

        ids = r.smembers(user_id)
        print(ids)

        cate = Stea.objects.get(id=id)
        # 循环随机数
        for i in ids:
            # 查看数据库名是否存在
            if r.hgetall(str(user_id) + str(i)):
                # 修改撤销状态
                cate.state = 1
                cate.save()
                return Response({'msg':'撤销成功'})
            return Response({'msg':'超过2分钟无法撤销'})





















